<?php
namespace app\api\controller\wine;

use app\api\controller\Controller;
use app\api\model\UserOauth;
use app\api\model\Wx as WxModel;
use app\common\model\store\Setting as SettingModel;
use think\App;

/**
 * 微信公众号被动回复
 */
class Wechat extends Controller{
    private $wechat;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->wechat = new \app\api\service\wine\Wechat();
    }

    // 微信公众号API
    public function receive(){
        /* 创建接口操作对象 */
        $wechat = & $this->wechat->load_wechat('Receive');

        /* 验证接口 */
        if ($wechat->valid() === FALSE) {
            // 接口验证错误，记录错误日志
            // log_message('ERROR', "微信被动接口验证失败，{$wechat->errMsg}[{$wechat->errCode}]");
            // 退出程序
            exit($wechat->errMsg);
        }

        /* 获取粉丝的openid */
        $openid = $wechat->getRev()->getRevFrom();

        /* 记录接口日志，具体方法根据实际需要去完善 */
// _logs();

        /* 分别执行对应类型的操作 */
        switch ($wechat->getRev()->getRevType()) {
            // 文本类型处理
            case \Wechat\WechatReceive::MSGTYPE_TEXT:
                $keys = $wechat->getRevContent();
                return $this->wechat->_keys($keys);
            // 事件类型处理
            case \Wechat\WechatReceive::MSGTYPE_EVENT:
                $event = $wechat->getRevEvent();
                return $this->wechat->_event(strtolower($event['event']));
            // 图片类型处理
            case \Wechat\WechatReceive::MSGTYPE_IMAGE:
                return $this->wechat->_image();
            // 发送位置类的处理
            case \Wechat\WechatReceive::MSGTYPE_LOCATION:
                return $this->wechat->_location();
            // 其它类型的处理，比如卡卷领取、卡卷转赠
            default:
                return $this->wechat->_default();
        }
    }

    // 获取微信code URL
    public function getWxCodeUrl(){
        $rUrl = input('url','','string');
        $state = input('state','','string');
        $scope = input('scope',0,'int');
        $url = $this->wechat->getWechatCode($rUrl,$state,$scope);
        return $this->renderSuccess(compact('url'),'成功获取微信code URL!');
    }

    // 判断是否关注公众号
    public function subscribe(){
        $userArr = $this->getLoginUser();
        $user_id = $userArr['user_id'];
        $openid = UserOauth::getOpenId($user_id);
        $gWxInfo = $this->wechat->getGUserInfo($openid);
        // 添加推荐海报url
        $config = SettingModel::getItem('poster', getStoreId());
        $gWxInfo['posterUrl'] =  $config['posterUrl'] ?? '';
        return $this->renderSuccess(compact('gWxInfo'),'成功获取公众号用户信息!');
    }
}
